import * as userModel from '../models/user';
import * as ossHelp from '../helps/third/aliyun/oss';
import * as smsHelp from '../helps/third/aliyun/sms';
import { EmptyException, InvalidException, SystemException } from '../helps/exception';
import cacheHelp from '../helps/cache';
import { cache } from '../config';

export function* ossTalkToken({ path }) {
  if (!path) throw EmptyException('Path empty');
  let result = ossHelp.uploadToken(ossHelp.BUCKETS.talk_bucket, path);
  return result;
}

export function* ossBaseToken({ path }) {
  if (!path) throw EmptyException('Path empty');
  let result = yield ossHelp.uploadToken(ossHelp.BUCKETS.base_bucket, path);
  return result;
}

export function* sendSMS({ mobile }) {
  if (!mobile) throw EmptyException('Mobile empty');
  let code = new Date().getTime();
  let valid_code = String.randomInt(4);

  yield smsHelp.send(mobile, smsHelp.TEMPLATEs.valid_code, {
    valid_code,
  });
  let result = yield cacheHelp.set(['mobile', mobile, { code }], { valid_code }, cache.expire);
  if (result) {
    return { code };
  } else {
    throw SystemException('cache fail');
  }
}

export function* validMobile({ mobile }) {
  if (!mobile) throw EmptyException('Mobile empty');
  let user = yield userModel.getByMobile(mobile);
  if (user) throw InvalidException('Mobile exist');
  return {};
}
